<?php

namespace App\Services\Stats\User;

use App\Core\Traits\Numeral;
use App\Models\Game\Platform\Org;
use App\Models\Game\Settlement\Info;
use App\Services\Service;
use App\Services\Traits\DatabaseMysql;
use App\Models\Admin\Stats\PlayerBet\Hour as StatsHour;
use App\Models\Admin\Stats\PlayerBet\Day as StatsDay;
use App\Models\Admin\Stats\PlayerBet\Month as StatsMonth;
use Helper\Timed;
use Ramsey\Uuid\Type\Time;

class PlayerBetService extends Service
{
    use DatabaseMysql, Numeral;

	/**
	 * 获取数据列表【小时】
	 *
	 * @param \Illuminate\Http\Request $request
	 * @param bool $export
	 * @return \Illuminate\Database\Eloquent\Collection[]|int[]|array[]
	 */
	public function hour($request, $export = false)
	{
		return $this->getList($request, 'hour', $export);
	}

	/**
	 * 获取数据列表【天】
	 *
	 * @param \Illuminate\Http\Request $request
	 * @param bool $export
	 * @return \Illuminate\Database\Eloquent\Collection[]|int[]|array[]
	 */
	public function day($request, $export = false)
	{
		return $this->getList($request, 'day', $export);
	}

	/**
	 * 获取数据列表【月】
	 *
	 * @param \Illuminate\Http\Request $request
	 * @param bool $export
	 * @return \Illuminate\Database\Eloquent\Collection[]|int[]|array[]
	 */
	public function month($request, $export = false)
	{
		$datetime = $request->input('datetime');

		if($datetime){
			date_default_timezone_set(Timed::getJsLocalTimezoneNameByCookie());
			$start_time = strtotime(date('Y-m-01', $datetime[0]));
			$end_time = strtotime(date('Y-m-01', strtotime('+1 month', $datetime[1])));
			if (!empty($datetime)) {
				$request->merge(['datetime' => [
					$start_time,
					$end_time - 1,
				]]);
			}
		}

		return $this->getList($request, 'month', $export);
	}

	/**
	 * 获取数据列表
	 *
	 * @param \Illuminate\Http\Request $request
	 * @param \Illuminate\Database\Eloquent\Builder $query
	 * @param bool $export
	 * @return \Illuminate\Database\Eloquent\Collection[]|int[]|array[]
	 */
	public function getList($request, $groupBy, $export)
	{
		$query = Info::query();
		$query->where('status', Info::STATUS_NORMAL)->where('player_type', Info::PLAYER_TYPE);
		// 筛选【平台】
		$this->makeWhereParamOrg($request, $query);
		// 筛选【平台】【排除】
		$this->makeWhereParamNot($request, 'plat_code_exclude', $query, 'plat_code');
		// 筛选【时间】
		if ($groupBy == 'month') {
			$this->makeWhereParamDatetimeTimeZoneStat($request, $query, 'end_time',  'datetime', '' ,'' , $groupBy);
		} else {
			$this->makeWhereParamDatetimeTimeZone($request, $query, 'end_time',  'datetime', '' ,'' , $groupBy);
		}
		// 筛选【币种】
		$this->makeWhereParam($request, 'currency', $query);
		// 筛选【币种】【排除】
		$this->makeWhereParamNot($request, 'currency_exclude', $query, 'currency');
		// 筛选【游戏】
		$this->makeWhereParam($request, 'game_id', $query);
		// 筛选【游戏】【排除】
		$this->makeWhereParamNot($request, 'game_id_exclude', $query, 'game_id');
		// 筛选【场景】
		$this->makeWhereParam($request, 'scene_id', $query);
		// 筛选【搜索】
		$this->makeWhereParamSearch($request, $query);

		// 统计数据
		$stats = $this->getStats(clone $query);

		// 排序
		$this->makeOrderParam($request, $query);

		//分页
		$this->makePaginationParam($request, $query);
		// 获取数据
		list($collection, $total) = $this->getData($request, $query, $groupBy);

		return [
			$collection,
			$total,
			$stats
		];
	}

	/**
	 * 获取统计信息
	 *
	 * @param \Illuminate\Database\Eloquent\Builder $query
	 * @return array
	 */
	private function getStats($query)
	{
		$sts = [];

		$usd = $query->getQuery()->selectRaw(implode(',', [
			'COUNT(*) as doc_count',
			"-IFNULL(CAST(SUM(usd->'$.gain_player') AS DECIMAL({$this->decimals()},{$this->precision()})),0) AS amount",
			"IFNULL(CAST(SUM(usd->'$.bet_base') AS DECIMAL({$this->decimals()},{$this->precision()})),0) AS bet_base",
			"IFNULL(CAST(SUM(usd->'$.bet_num') AS DECIMAL({$this->decimals()},{$this->precision()})),0) AS bet_num",
			"IFNULL(CAST(SUM(usd->'$.gain_player') AS DECIMAL({$this->decimals()},{$this->precision()})),0) AS gain_player",
		]))
			->first();


		// 分币种
		$rows = $query->getQuery()->selectRaw(implode(',', [
			'-SUM(gain_player) as amount',
			'SUM(bet_num) as bet_num',
			'SUM(bet_base) as bet_base',
			'COUNT(*) as doc_count',
			'SUM(gain_player) as gain_player',
			"-IFNULL(CAST(SUM(usd->'$.gain_player') AS DECIMAL({$this->decimals()},{$this->precision()})),0) AS usd_amount",
			"IFNULL(CAST(SUM(usd->'$.bet_base') AS DECIMAL({$this->decimals()},{$this->precision()})),0) AS usd_bet_base",
			"IFNULL(CAST(SUM(usd->'$.bet_num') AS DECIMAL({$this->decimals()},{$this->precision()})),0) AS usd_bet_num",
			"IFNULL(CAST(SUM(usd->'$.gain_player') AS DECIMAL({$this->decimals()},{$this->precision()})),0) AS usd_gain_player",
			'currency',
		]))
			->groupBy(['currency'])
			->get();


		collect($rows)->map(function ($row)use(&$usd, &$sts) {
			if(!isset($sts[$row['currency']])){
				$sts[$row['currency']] = [
					'amount' => 0,
					'bet_base' => 0,
					'bet_num' => 0,
					'doc_count' => 0,
					'gain_player' => 0,
					'currency' => $row['currency'],
				];
			}

			$sts[$row['currency']]['amount'] += $row['amount'];
			$sts[$row['currency']]['bet_base'] += $row['bet_base'];
			$sts[$row['currency']]['bet_num'] += $row['bet_num'];
			$sts[$row['currency']]['doc_count'] += $row['doc_count'];
			$sts[$row['currency']]['gain_player'] += $row['gain_player'];
		});

		return [
			'usd' => $usd,
			'sts' => $sts,
		];
	}

	/**
	 * 获取数据和总条数
	 *
	 * @param \Illuminate\Database\Eloquent\Builder $query
	 * @return array
	 */
	private function getData($request, $query, $groupBy)
	{
		//转换指定时区
		date_default_timezone_set(Timed::getTimezoneName());

		switch ($groupBy){
			case 'day':
				$columns[] ="DATE(CONVERT_TZ(DATE_FORMAT(FROM_UNIXTIME(end_time), '%Y-%m-%d %H:%i:%s'), '+08:00', '".Timed::getTimeCode()."')) as timed";
				break;
			case 'hour':
				$columns[] ="DATE_FORMAT(CONVERT_TZ(FROM_UNIXTIME(end_time), '+08:00', '".Timed::getTimeCode()."'), '%Y-%m-%d %H:00:00') AS timed";
				break;
			case 'month':
				$columns[] ="DATE_FORMAT(CONVERT_TZ(FROM_UNIXTIME(end_time), '+08:00', '".Timed::getTimeCode()."'), '%Y-%m-01') AS timed";
				break;
		}
		$columns[] = 'currency';
		$columns[] = 'plat_code';
		$columns[] = 'uid';
		$columns[] = 'game_id';
		$columns[] = 'account_id';
		$columns[] = 'COUNT(*) as doc_count';
		$columns[] = 'IFNULL(SUM(gain_player),0) as gain_player';
		$columns[] = '-IFNULL(SUM(gain_player),0) as amount';
		$columns[] = 'IFNULL(SUM(bet_base),0) as bet_base';
		$columns[] = 'IFNULL(SUM(bet_num),0) as bet_num';
		$columns[] = "IFNULL(CAST(SUM(usd->'$.gain_player') AS DECIMAL({$this->decimals()},{$this->precision()})),0) AS usd_gain_player";
		$columns[] = "IFNULL(CAST(SUM(usd->'$.bet_num') AS DECIMAL({$this->decimals()},{$this->precision()})),0) AS usd_bet_num";
		$columns[] = "IFNULL(CAST(SUM(usd->'$.bet_base') AS DECIMAL({$this->decimals()},{$this->precision()})),0) AS usd_bet_base";

		$query->groupByRaw('timed, currency, plat_code, uid, game_id');

		return Info::dbConnection()->transaction(function () use ($request, $query, $columns, $groupBy) {
			// 查询数据
			$collection = $query->getQuery()
				->selectRaw('SQL_CALC_FOUND_ROWS ' . implode(',', $columns))
				->get();
//            Timed::toSql($collection);

			// 数据条数
			$total = (int)Info::dbConnection()->select("SELECT FOUND_ROWS() as `row_count`")[0]['row_count'];

			$collectionArr = $collection->toArray();
			//查询org
			$plat_codes = array_column($collectionArr, 'plat_code');
			$orgs = Org::whereIn('code', $plat_codes)->select(['code', 'name'])->get()->toArray();
			$orgArr = array_column($orgs, 'name', 'code');



			$collection->transform(function ($item)use($request, $groupBy, $orgArr) {

				$item['timed'] = strtotime($item['timed']);

				return $item + ['usd'=>
					                [
						                'amount' => -$item['usd_gain_player'],
						                'bet_base' => $item['usd_bet_base'],
						                'bet_num' => $item['usd_bet_num'],
						                'gain_player' => $item['usd_gain_player'],
					                ]
					] + [
						'time_zone' => Timed::getTimezoneName(),
						'group_by' => $groupBy,
					] + [
						'org' =>[
							'code' => $item['plat_code'],
							'name' => isset($orgArr[$item['plat_code']]) ? $orgArr[$item['plat_code']] : $item['plat_code'],
						],
					];
			});

			return [$collection, $total];
		});
	}
}
